<template>
  <el-dialog title="选择成员" v-model="visibleDialog" :width="600" append-to-body class="promoter_person" @open="openDialog">
    <div class="person_body clear">
      <div class="person_tree l">
        <el-tabs v-model="activeTab" class="demo-tabs">
          <el-tab-pane label="用户列表" name="user" :disabled="assigneeType !== 'user'">
            <el-tree
              ref="userTreeRef"
              class="tree-no-expand"
              :data="userList"
              :props="treeProps"
              node-key="id"
              check-strictly
              show-checkbox
              default-expand-all
              @check-change="handleChecked"
              style="width: 100%"
            />
          </el-tab-pane>
          <el-tab-pane label="角色列表" name="role" :disabled="assigneeType !== 'role'">
            <el-tree
              ref="roleTreeRef"
              class="tree-no-expand"
              :data="roleList"
              :props="treeProps"
              node-key="id"
              check-strictly
              show-checkbox
              default-expand-all
              @check-change="handleChecked"
              style="width: 100%"
            />
          </el-tab-pane>
          <el-tab-pane label="部门组织" name="depart" :disabled="assigneeType !== 'depart'">
            <el-tree ref="departTreeRef" :data="departList" :props="treeProps" node-key="id" check-strictly show-checkbox default-expand-all @check-change="handleChecked" style="width: 100%" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="select-result l">
        <p class="clear">
          已选（{{ total }}）
          <a @click="delList">清空</a>
        </p>
        <ul>
          <template v-for="({ type, data, cancel }, index) in resList" :key="type">
            <template v-if="type === 'role'">
              <li v-for="item in data" :key="index + '-' + item.id">
                <el-icon color="#409efc" class="type-icon"><Headset /></el-icon>
                <span>{{ item.name }}</span>
                <el-icon class="del-btn" @click="cancel(item)"><CircleClose /></el-icon>
              </li>
            </template>
            <template v-if="type === 'depart'">
              <li v-for="item in data" :key="index + '-' + item.id">
                <el-icon color="#409efc" class="type-icon"><OfficeBuilding /></el-icon>
                <span>{{ item.name }}</span>
                <el-icon class="del-btn" @click="cancel(item)"><CircleClose /></el-icon>
              </li>
            </template>
            <template v-if="type === 'user'">
              <li v-for="item in data" :key="index + '-' + item.id">
                <el-icon color="#409efc" class="type-icon"><User /></el-icon>
                <span>{{ item.name }}</span>
                <el-icon class="del-btn" @click="cancel(item)"><CircleClose /></el-icon>
              </li>
            </template>
          </template>
        </ul>
      </div>
    </div>
    <template #footer>
      <el-button @click="$emit('update:visible', false)">取 消</el-button>
      <el-button type="primary" @click="saveDialog">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useStore } from 'vuex'
import { CircleClose, OfficeBuilding, Headset, User } from '@element-plus/icons-vue'

let props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  users: {
    type: Array,
    default: () => []
  },
  departs: {
    type: Array,
    default: () => []
  },
  roles: {
    type: Array,
    default: () => []
  },
  assigneeType: {
    type: String,
    default: 'user'
  }
})
let emits = defineEmits(['update:visible', 'change'])
const store = useStore()
let visibleDialog = computed({
  get() {
    return props.visible
  },
  set() {
    emits('update:visible', false)
  }
})
const assigneeType = computed(() => props.assigneeType)

// 列表数据
const treeProps = ref({
  label: 'name',
  value: 'id'
})
const userTreeRef = ref(null)
const departTreeRef = ref(null)
const roleTreeRef = ref(null)
const userList = computed(() => store.state.flow.operatorData.user)
const departList = computed(() => store.state.flow.operatorData.depart)
const roleList = computed(() => store.state.flow.operatorData.role)
const checkedUserList = ref([])
const checkedRoleList = ref([])
const checkedDepartList = ref([])

// 切换tab
const activeTab = ref('user')

// 选择事件
let total = computed(() => checkedDepartList.value.length + checkedUserList.value.length + checkedRoleList.value.length)
const handleChecked = (data, checked) => {
  if (data.operatorType === 'user') {
    changeChecked(checkedUserList.value, data, checked)
  } else if (data.operatorType === 'depart') {
    changeChecked(checkedDepartList.value, data, checked)
  } else if (data.operatorType === 'role') {
    changeChecked(checkedRoleList.value, data, checked)
  }
}

const changeChecked = (arr, data, checked) => {
  if (checked) {
    arr.push(data)
  } else {
    let index = arr.findIndex(item => item.id === data.id)
    if (index !== -1) {
      arr.splice(index, 1)
    }
  }
}

// 已选结果
let resList = computed(() => {
  let data = [
    {
      type: 'user',
      data: checkedUserList.value,
      cancel: item => {
        // 设置选中转台后会自动调用handleChecked方法处理数据
        userTreeRef.value.setChecked(item.id, false)
      }
    },
    {
      type: 'role',
      data: checkedRoleList.value,
      cancel: item => {
        roleTreeRef.value.setChecked(item.id, false)
      }
    },
    {
      type: 'depart',
      data: checkedDepartList.value,
      cancel: item => {
        departTreeRef.value.setChecked(item.id, false)
      }
    }
  ]
  return data
})

// 清空已选
const delList = () => {
  checkedUserList.value = []
  userTreeRef.value.setCheckedKeys([])
  checkedDepartList.value = []
  departTreeRef.value.setCheckedKeys([])
  checkedRoleList.value = []
  roleTreeRef.value.setCheckedKeys([])
}

// 保存选择
let saveDialog = () => {
  const users = checkedUserList.value.map(item => item.id)
  const departs = checkedDepartList.value.map(item => item.id)
  const roles = checkedRoleList.value.map(item => item.id)
  emits('change', users, departs, roles)
}

// 打开弹窗,初始化节点复选框状态
const openDialog = () => {
  activeTab.value = assigneeType.value
  userTreeRef.value?.setCheckedKeys(props.users, true)
  departTreeRef.value?.setCheckedKeys(props.departs, true)
  roleTreeRef.value?.setCheckedKeys(props.roles, true)
}
</script>
<style lang="scss" scoped>
.promoter_person .el-dialog__body {
  padding: 10px 20px 14px 20px;
  .person_body {
    display: flex;
    flex-wrap: nowrap;
    border: 1px solid #f5f5f5;
    height: 500px;
    .person_tree {
      padding: 0px 12px;
      width: 50%;
      height: 100%;
      border-right: 1px solid #f5f5f5;
    }
    .select-result {
      padding: 0 12px;
      width: 50%;
      height: 100%;
      font-size: 14px;
    
      ul {
        height: 460px;
        overflow-y: auto;
    
        li {
          margin: 11px 0 13px 0;
          line-height: 17px;
          display: flex;
          align-items: center;
          .type-icon {
            margin-right: 4px;
          }
          .del-btn {
            margin-left: auto;
            cursor: pointer;
          }
        }
      }
    
      p {
        line-height: 38px;
        border-bottom: 2px solid #e4e7ed;
    
        a {
          float: right;
        }
      }
    }
  }
}
::v-deep .el-tree.tree-no-expand .el-tree-node .el-tree-node__expand-icon {
  display: none;
}
</style>
